package utilities;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import netcom.messages.Message;



/**Serializable Utility Class
* 
* Serialize and deserialize a message from and to a byte array
* 
* TBD: 	adding secure serialize to guarantee secure exchange between devices
* 		security could be done by using RSA algorithm with share keys
* 
* NB:	Serializable class exchange with different devices works only in Android version 4.x
* 
* @author      Alan Ferrari <alan.ferrari@supsi.ch>
* @version     1.0                 
* @since       2013-04-18    
*/
public class SerializableClassUtility {

	
	/**
	 * Serialize a message class into byte array
	 * @param mess instance of the Message class
	 * @return	byte array with the serielized class
	 */
	public static byte[] getBytesFromClass(Message mess){
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out = null;
		try {
		  out = new ObjectOutputStream(bos);   
		  out.writeObject(mess);
		  byte[] yourBytes = bos.toByteArray();
		  
		  out.close();
		  bos.close();
		  
		  //return byte array
		  return yourBytes;
		  
		} catch (IOException e) { e.printStackTrace();
		} 
		
		return null;
	}
	
	/**
	 * Deserialize the class from a byte array, return null
	 * if the process fails.
	 * @param bytes array representing the serialized class
	 * @return	an Object instance (check if the object is instace of message)
	 */
	public  static Object getMessaFromBytes(byte[] bytes){
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInput in = null;
		
		  try {
			in = new ObjectInputStream(bis);
			Object o = in.readObject(); 
			bis.close();
			in.close();
			
			return o;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		  
		//return null if the serialization fails
		return null;
	} 
	
	

	/**
	 * Serialize a message class into byte array and cyper the array
	 * 
	 * NB: is only a method stub
	 * 
	 * @param mess instance of the Message class
	 * @return	byte array with the secured-serialized class
	 */
	public static Object getSecureMessageFromBytes(byte[] bytes, int key){
		return null;
	}
	
	/**
	 * Decipher and Deserialize the class from a byte array, return null
	 * if the process fails.
	 * 
	 * NB: is only  a method stub
	 * 
	 * @param bytes array representing the secured-serialized class
	 * @return	an Object instance (check if the object is instance of message)
	 */
	public static byte[] getSecureByteFromClass(Message m, int key){
		return null;
	}

}
